<?php namespace App\Http\Controllers\Api\Admin;

use App\Admin;
use App\Banner;
use App\BooksChapter;
use App\BooksInfo;
use App\Classify;
use App\Http\Controllers\Controller;
use App\RechargePackage;
use App\User;
use App\UserVip;
use App\VipRule;
use Auth;
use Illuminate\Http\Request;

class SystemController extends Controller
{
    public function setBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $title   = $request->get('title');
        $linkUrl = $request->get('link_url');
        $sort    = $request->get('sort');
        $imgId   = $request->get('img_id');
        $id      = !is_null($request->get('id'))?$request->get('id'):0;

        $thatBanner = Banner::whereId(trim($id))->first();

        if(!$thatBanner)
            $thatBanner = new Banner();

        if(!is_null($title))$thatBanner->title = $title;
        if(!is_null($linkUrl))$thatBanner->link_url = $linkUrl;
        if(!is_null($sort))$thatBanner->sort = $sort;
        if(!is_null($imgId))$thatBanner->img_id = $imgId;
        $thatBanner->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$thatBanner]);
    }

    public function delBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Banner $thatBanner */
        $thatBanner = Banner::whereId($id)->first();

        if(!$thatBanner)
            return response()->json(["level"=>"error","message"=>"该banner不存在！"]);

        $thatBanner->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatBanner]);
    }

    public function setAdmin(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $username = $request->get('username');
        $password = $request->get('password');
        $repass   = $request->get('repass');

        if($password != $repass)
            return response()->json(['level'=>'error','message' => '两次密码不一致！']);

        /** @var Admin $hasUser */
        $hasUser = Admin::whereUsername($username)->first();
        if($hasUser){
            return response()->json(['level'=>'error','message' => '当前管理员账号已存在']);
        }

        $thatAdmin = new Admin();
        $thatAdmin->username = $username;
        $thatAdmin->password = bcrypt($password);
        $thatAdmin->status = 2;
        $thatAdmin->save();

        return response()->json(['level'=>'success','message'=>'添加成功','data'=>$thatAdmin]);
    }

    public function delAdmin(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Admin $thatAdmin */
        $thatAdmin = Admin::whereId($id)->first();

        if(!$thatAdmin)
            return response()->json(["level"=>"error","message"=>"该管理员不存在！"]);

        if($thatAdmin->status == 1)
            return response()->json(["level"=>"error","message"=>"该管理员不能删除！"]);


        $thatAdmin->forceDelete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatAdmin]);
    }

    public function setBooksWord(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name             = $request->get('name');
        $desc             = $request->get('desc');
        $imgId            = $request->get('img_id');
        $author           = $request->get('author');
        $type             = $request->get('type');
        $isComplete       = $request->get('is_complete');
        $homeShow         = $request->get('home_show');
        $isFeatured       = $request->get('is_featured');
        $booksCoinPrice   = $request->get('books_coin_price');
        $status           = $request->get('status');
        $id               = !is_null($request->get('id')) ? $request->get('id') : 0;
        $classifyId       = $request->get('classifyId');

        $newBooksInfo = BooksInfo::whereId($id)->first();
        if(!$newBooksInfo)
            $newBooksInfo = new BooksInfo();

        if(!is_null($name))$newBooksInfo->name                         = $name;
        if(!is_null($desc))$newBooksInfo->desc                         = $desc;
        if(!is_null($imgId))$newBooksInfo->img_id                      = $imgId;
        if(!is_null($author))$newBooksInfo->author                     = $author;
        if(!is_null($type))$newBooksInfo->type                         = $type;
        if(!is_null($isComplete))$newBooksInfo->is_complete            = $isComplete;
        if(!is_null($homeShow))$newBooksInfo->home_show                = $homeShow;
        if(!is_null($isFeatured))$newBooksInfo->is_featured            = $isFeatured;
        if(!is_null($booksCoinPrice))$newBooksInfo->books_coin_price   = $booksCoinPrice;
        if(!is_null($status))$newBooksInfo->status                     = $status;
        if(!is_null($classifyId))$newBooksInfo->classify_id            =$classifyId;
        $newBooksInfo->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newBooksInfo]);
    }

    public function delBooksWord(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Admin $thatAdmin */
        $thatBooksInfo = BooksInfo::whereId($id)->first();

        if(!$thatBooksInfo)
            return response()->json(["level"=>"error","message"=>"该书籍不存在！"]);

        $thatBooksInfo->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatBooksInfo]);
    }

    public function setBooksChapter(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name              = $request->get('name');
        $wordCount         = $request->get('word_count');
        $audioId           = $request->get('audio_id');
        $content           = $request->get('content');
        $booksInfoId       = !is_null($request->get('books_info_id')) ? $request->get('books_info_id') : 0;
        $booksCoinPrice    = $request->get('books_coin_price');
        $status            = $request->get('status');
        $id                = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var BooksChapter $newBooksChapter */
        $newBooksChapter = BooksChapter::whereId($id)->first();

        /** @var BooksChapter $isBooksChapterSort */
        $booksChapterSort = BooksChapter::whereBooksInfoId($booksInfoId)->count();

        if(!$newBooksChapter){
            $newBooksChapter = new BooksChapter();
            $newBooksChapter->sort                                               = $booksChapterSort+1;
        }

        if(!is_null($name))$newBooksChapter->name                            = $name;
        if(!is_null($wordCount))$newBooksChapter->word_count                 = $wordCount;
        if(!is_null($audioId))$newBooksChapter->audio_id                     = $audioId;
        if(!is_null($content))$newBooksChapter->content                      = $content;
        if(!is_null($booksInfoId))$newBooksChapter->books_info_id            = $booksInfoId;
        if(!is_null($booksCoinPrice))$newBooksChapter->books_coin_price      = $booksCoinPrice;
        if(!is_null($status))$newBooksChapter->status                        = $status;
        $newBooksChapter->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newBooksChapter]);
    }

    public function delBooksChapter(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Admin $thatAdmin */
        $thatBooksChapter = BooksChapter::whereId($id)->first();

        if(!$thatBooksChapter)
            return response()->json(["level"=>"error","message"=>"该章节不存在！"]);

        $thatBooksChapter->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatBooksChapter]);
    }

    public function setRechargePackage(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name                  = $request->get('name');
        $amountMoney           = $request->get('amount_money');
        $booksCoin             = $request->get('books_coin');
        $giftBookCoin          = $request->get('gift_books_coin');
        $remark                = $request->get('remark');
        $sort                  = $request->get('sort');
        $status                = $request->get('status');
        $id                    = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newRechargePackage = RechargePackage::whereId($id)->first();
        if(!$newRechargePackage)
            $newRechargePackage = new RechargePackage();

        if(!is_null($name))$newRechargePackage->name                                  = $name;
        if(!is_null($amountMoney))$newRechargePackage->amount_money                   = $amountMoney;
        if(!is_null($booksCoin))$newRechargePackage->books_coin                       = $booksCoin;
        if(!is_null($giftBookCoin))$newRechargePackage->gift_books_coin               = $giftBookCoin;
        if(!is_null($remark))$newRechargePackage->remark                              = $remark;
        if(!is_null($sort))$newRechargePackage->sort                                  = $sort;
        if(!is_null($status))$newRechargePackage->status                              = $status;
        $newRechargePackage->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newRechargePackage]);
    }

    public function delRechargePackage(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Admin $thatAdmin */
        $thatRechargePackage = RechargePackage::whereId($id)->first();

        if(!$thatRechargePackage)
            return response()->json(["level"=>"error","message"=>"该套餐不存在！"]);

        $thatRechargePackage->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatRechargePackage]);
    }

    public function addClassify(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $name = $request->get("name");
        $sort = $request->get('sort');
        $id   = !is_null($request->get('id'))?$request->get('id'):0;

        $newClassify = Classify::whereId(trim($id))->first();

        if(!$newClassify)
            $newClassify = new Classify();

        if(!is_null($name))$newClassify->name = $name;
        if(!is_null($sort))$newClassify->sort = $sort;
        $newClassify->save();

        return response()->json(["level"=>"success","message"=>"添加或修改成功","data"=>$newClassify]);
    }

    public function delClassify(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;
        $thatClassify =Classify::whereId($id)->first();

        if(!$thatClassify)
            return response()->json(["level"=>"error","message"=>"该分类不存在！"]);

        $thatClassify->delete();

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    public function setUserFree(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var User $thisUser */
        $thisUser = User::whereId($id)->first();
        if(!$thisUser)
            return response()->json(['level' => 'error','message' => '该用户不存在']);

        if($thisUser->is_free == 1){
            $thisUser->is_free = 0;
            $thisUser->save();
        }else{
            $thisUser->is_free = 1;
            $thisUser->save();
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisUser]);
    }

    public function setVipRule(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $name    = $request->get('name');
        $vipTime = $request->get('vip_time');
        $money   = $request->get('money');
        $sort    = $request->get('sort');
        $remark  = $request->get('remark');
        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newVipRule = VipRule::whereId($id)->first();
        if(!$newVipRule)
            $newVipRule = new VipRule();

        if(!is_null($name))$newVipRule->name              = $name;
        if(!is_null($vipTime))$newVipRule->vip_time       = $vipTime;
        if(!is_null($money))$newVipRule->money            = $money;
        if(!is_null($sort))$newVipRule->sort              = $sort;
        if(!is_null($request))$newVipRule->remark         = $remark;
        $newVipRule->type                                 = 'global_vip';
        $newVipRule->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newVipRule]);
    }

    public function delVipRule(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisVipRule = VipRule::whereId($id)->first();
        if(!$thisVipRule)
            return response()->json(['level' => 'error','message' => '该会员规则不存在']);

        $thisVipRule->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisVipRule]);
    }

    public function setPackageRule(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $name       = $request->get('name');
        $vipTime    = $request->get('vip_time');
        $money      = $request->get('money');
        $classifyId = $request->get('classify_id');
        $sort       = $request->get('sort');
        $remark     = $request->get('remark');
        $id         = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newVipRule = VipRule::whereId($id)->first();
        if(!$newVipRule)
            $newVipRule = new VipRule();

        if(!is_null($name))$newVipRule->name              = $name;
        if(!is_null($vipTime))$newVipRule->vip_time       = $vipTime;
        if(!is_null($money))$newVipRule->money            = $money;
        if(!is_null($classifyId))$newVipRule->classify_id = $classifyId;
        if(!is_null($sort))$newVipRule->sort              = $sort;
        if(!is_null($request))$newVipRule->remark         = $remark;
        $newVipRule->type                                 = 'classify_vip';
        $newVipRule->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newVipRule]);
    }

    public function delPackageRule(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisVipRule = VipRule::whereId($id)->first();
        if(!$thisVipRule)
            return response()->json(['level' => 'error','message' => '该会员规则不存在']);

        $thisVipRule->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisVipRule]);
    }

    public function setUserVip(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $userId = !is_null($request->get('user_id')) ? $request->get('user_id') : 0;
        $vipId  = !is_null($request->get('vip_id')) ? $request->get('vip_id') : 0;

        $thatVipRule = VipRule::whereId($vipId)->whereType("global_vip")->first();
        if(!$thatVipRule)
            return response()->json(['level' => 'error','message' => 'vip规则不存在！']);

        $todayTime = date("Y-m-d H:i:s",time());
        $userVip = UserVip::whereType("global_vip")->whereUserId($userId)->where("start_time","<",$todayTime)->where("end_time",">",$todayTime)->first();
        if(!$userVip){
            if($thatVipRule->vip_time == -1){
                $endTime = date("Y-m-d H:i:s",time() + 86400 * 5 * 365);
            }else{
                $endTime = date("Y-m-d H:i:s",time() + 86400 * $thatVipRule->vip_time);
            }
            $userVip = new UserVip();
            $userVip->user_id = $userId;
            $userVip->start_time = $todayTime;
            $userVip->end_time = $endTime;
            $userVip->type     = "global_vip";
            $userVip->save();
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $userVip]);
    }

    public function delUserVip(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $vipId  = !is_null($request->get('vip_id')) ? $request->get('vip_id') : 0;

       $thatUserVip = UserVip::whereId($vipId)->first();
       if($thatUserVip)
           $thatUserVip->delete();

        return response()->json(['level' => 'success','message' => '取消成功']);
    }
}